<?php

namespace frontendx\models;

/**
 * @author  shuang
 * @date    2016-11-15 21:20:11
 * @version V1.0
 * @desc    
 */
use common\models\UserPayRecordHy;
use frontendx\models\WB_UserAccountHy;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;

class WB_UserPayRecordHy extends UserPayRecordHy {

    //交易类型
    public static $paytype = [1 => "充值", 2 => "支出"];
    //交易类别
    public static $class_type = [
        1 => ["classnote" => "完成任务", "desc" => "完成任务"],
        2 => ["classnote" => "申诉返现", "desc" => "申诉返现"],
        3 => ["classnote" => "投诉退还", "desc" => "投诉退还佣金"],
        4 => ["classnote" => "平台操作", "desc" => "余额转入提现"]
    ];

    /*
     * 设置表操作行为动作
     * return array
     */

    public function behaviors() {
        return[
            [
                'class' => TimestampBehavior::className()
            ]
        ];
    }

    /*
     * 添加交易记录 、 更新账户金额
     * @params $userid
     * @params $amount
     * @params $type
     * @params $class_type
     */

    public static function createRecord($userid, $amount, $type = 1, $class_type = 1, $note = null, $taskid = null) {
        try {
            $userpayrecord = new WB_UserPayRecordHy();
            $userpayrecord->userid = $userid;
            $userpayrecord->type = $type;
            $userpayrecord->class_type = $class_type;
            $userpayrecord->amount = $amount;
            $userpayrecord->taskid = $taskid;
            $userpayrecord->description = $note ? $note : ArrayHelper::getValue(WB_UserPayRecordHy::$class_type, "$class_type.desc");
            if ($userpayrecord->save()) {
                $uesraccount = WB_UserAccountHy::find()->where("userid=" . $userid)->one();
                if ($uesraccount) {
                    $uesraccount->amount = $uesraccount->amount + $amount;
                    return $uesraccount->save();
                } else {
                    $useraccount = new WB_UserAccountHy();
                    $useraccount->userid = $userid;
                    $useraccount->amount = 0;
                    $useraccount->offline_amount = 0;
                    return $useraccount->save();
                }
            } else {
                return false;
            }
        } catch (Exception $ex) {
            throw $ex;
        }
    }

    /*
     * 查询会员完成的任务记录
     */

    public static function searchTaskCompentRecord() {
        $query = new \yii\db\Query();
        $query->from(WB_UserPayRecordHy::tableName() . " as a");
        $query->where("a.type=:type and a.class_type=:class_type and a.taskid is not null", [":type" => 1, "class_type" => 1]);
        $query->leftJoin(WB_Task::tableName() . " as b", "a.taskid=b.id");
        $query->leftJoin(\common\models\User::tableName() . " as c", "a.userid=c.id");
        $query->orderBy("a.created_at desc");
        $query->limit(10);
        $query->select("a.*,b.title,c.username");
        return $query->all();
    }

}
